const express = require("express");
const router = express.Router();
const path = require('path');
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const axios = require("axios");
const CryptoJS = require("crypto-js");
const crypto = require("crypto");

const config = require("../config");
const { content } = require("googleapis/build/src/apis/content/index.js");
const apiKey = process.env.OPENAI_API_KEY;
// 配置 multer 的存储设置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件上传目录
        cb(null, "/home/wwwroot/default/beautyImages");
    },
    filename: function (req, file, cb) {
        // 生成文件名
        cb(null, Date.now() + "-" + file.originalname);
    },
});

const upload = multer({ storage: storage });

// 创建文件上传的 POST 接口
router.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;
    const { pk } = req.body;
    if (!file) {
        return res.status(400).send("请上传一个文件。");
    }
    let fileUrl = ''
    //安卓qrcode 放ins2服务器

    fileUrl = `https://insdoss.freeapptools.com/beautyImages/${file.filename}`;



    // 返回文件存储地址
    res.send({
        code: 0,
        message: "success",
        fileUrl: fileUrl,
    });
});
 
router.post('/submitSurveyResponse', async (req, res) => {
    const { language, country, isp, questionnaireResponses, app_version } = req.body
    let content = {}
    content.id = utils.createId();
    content.language = language;
    content.country = country;
    content.isp = isp;
    content.questionnaireResponses = questionnaireResponses;
    content.app_version = app_version;
    content.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql("iptv_questionnaire", content);
    
    let result = await utils.query(text, values);
    if (result.affectedRows == 1) {
        res.send({
            code: 0,
            msg: "success",
        });

    }   
})

router.post('/getList', async (req, res) => {
    const { dateRange, country, language } = req.body;
    let sql = `SELECT * FROM iptv_questionnaire WHERE 1=1`;
    let params = [];

    if (country) {
        sql += " AND country = ?";
        params.push(country);
    }
    if (language) {
        sql += " AND language = ?";
        params.push(language);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');

        sql += ` AND update_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    try {
        const results = await mysqlQuery(sql, params);

        res.send(
            utils.returnData({
                data: results
            })
        );
    } catch (error) {
        console.error('Error fetching token usage data:', error);
        res.status(500).send('Internal Server Error');
    }
});
//获取语种列表
router.post("/getLanguageList", async (req, res) => {
    let sql = `SELECT language FROM iptv_questionnaire GROUP BY language;`;
    let result = await mysqlQuery(sql, [])
    res.send(
        utils.returnData({
            data: result,
        })
    );
});
router.post("/getCountryList", async (req, res) => {
    let sql = `SELECT country FROM iptv_questionnaire GROUP BY country;`;
    let result = await mysqlQuery(sql, [])
    res.send(
        utils.returnData({
            data: result,
        })
    );
});
async function mysqlQuery(sql, arr) {

    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {

            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
router.post('/generateSign', async (req, res) => {
    const { user_id, role_id, timestamp, token } = req.body;
    let params = {
        user_id: Number(user_id),
        role_id: Number(role_id),
        timestamp: String(timestamp)
    };
    // 去除 sign 字段，node这里无自动sign
    let keys = Object.keys(params).sort();
    let kvArr = keys.map(key => `${key}=${params[key]}`);
    const signStr = kvArr.join('&');
    // 2. 拼接 token (即 salt)
    const finStr = signStr + token;
    // 3. md5哈希
    const sign = crypto.createHash('md5').update(finStr).digest('hex');
    res.send({ sign: sign })
})
 
module.exports = router;
